package com.hengxinguotong.zhihuichengjian.ui.safetystudy;

import com.github.mikephil.charting.formatter.ValueFormatter;
import com.hengxinguotong.zhihuichengjian.customtimepicker.TimePickerActivity;
import com.hengxinguotong.zhihuichengjian.customtimepicker.bean.DayTimeEntity;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.LegendAdapter;
import com.hengxinguotong.zhihuichengjian.bean.ChartBean;
import com.hengxinguotong.zhihuichengjian.bean.LegendBean;
import com.hengxinguotong.zhihuichengjian.bean.Statistics;
import com.hengxinguotong.zhihuichengjian.bean.StatisticsChartBean;
import com.hengxinguotong.zhihuichengjian.bean.StatisticsChartBeanRes;
import com.hengxinguotong.zhihuichengjian.bean.StatisticsRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.MPChartUtils;
import com.hengxinguotong.zhihuichengjian.utils.PieChartManager;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2018/11/5
 */

public class StatisticsAndQueryActivity extends BaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener
{
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.total_person_now_tv)
    HXTextView totalPersonNowTv;
    @BindView(R.id.total_person_history_tv)
    HXTextView totalPersonHistoryTv;
    @BindView(R.id.total_person_train_tv)
    HXTextView totalPersonTrainTv;
    @BindView(R.id.train_percent_tv)
    HXTextView trainPercentTv;
    @BindView(R.id.total_train_tv)
    HXTextView totalTrainTv;
    @BindView(R.id.total_train_hour_tv)
    HXTextView totalTrainHourTv;
    @BindView(R.id.avg_person_train_hour_tv)
    HXTextView avgPersonTrainHourTv;
    @BindView(R.id.total_person_exam_tv)
    HXTextView totalPersonExamTv;
    @BindView(R.id.total_exam_pass_tv)
    HXTextView totalExamPassTv;
    @BindView(R.id.exam_pass_percent_tv)
    HXTextView examPassPercentTv;
    @BindView(R.id.total_person_now)
    HXTextView totalPersonNow;
    @BindView(R.id.total_person_history)
    HXTextView totalPersonHistory;
    @BindView(R.id.total_person_train)
    HXTextView totalPersonTrain;
    @BindView(R.id.train_percent)
    HXTextView trainPercent;
    @BindView(R.id.total_train)
    HXTextView totalTrain;
    @BindView(R.id.total_train_hour)
    HXTextView totalTrainHour;
    @BindView(R.id.avg_person_train_hour)
    HXTextView avgPersonTrainHour;
    @BindView(R.id.total_person_exam)
    HXTextView totalPersonExam;
    @BindView(R.id.total_exam_pass)
    HXTextView totalExamPass;
    @BindView(R.id.exam_pass_percent)
    HXTextView examPassPercent;
    @BindView(R.id.statistics_rg)
    RadioGroup statisticsRg;
    @BindView(R.id.train_layout)
    LinearLayout trainLayout;
    @BindView(R.id.exam_layout)
    LinearLayout examLayout;
    @BindView(R.id.employee_layout)
    LinearLayout employeeLayout;
    @BindView(R.id.pie_chart)
    PieChart pieChart;
    @BindView(R.id.bar_chart)
    BarChart barChart;
    @BindView(R.id.start_end_date)
    HXTextView startDndDate;
    @BindView(R.id.name_tv)
    HXTextView nameTv;
    @BindView(R.id.pie_chart_legend_rv)
    RecyclerView pieChartLegendRv;

    private DayTimeEntity startDay, stopDay;
    private String startTime,//起始日期
            endTime;//结束日期
    private int type;

    private YAxis leftAxis;             //左侧Y轴
    private YAxis rightAxis;            //右侧Y轴
    private XAxis xAxis;                //X轴
    private Legend legend;              //图例
    private LimitLine limitLine;        //限制线

    private List<LegendBean> pieLegendList;
    private LegendAdapter pieAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistics_and_query);
        ButterKnife.bind(this);
        initView();
        initBarChart(barChart);
        type = 1 ;
        initDate();
    }

    private void initView(){
        String title = getIntent().getStringExtra("title");
        titleTv.setText(title);

        statisticsRg.setOnCheckedChangeListener(this);

        nameTv.setText(R.string.total_person_train);
    }

    private void showLayout(int id){
        trainLayout.setVisibility(View.GONE);
        examLayout.setVisibility(View.GONE);
        employeeLayout.setVisibility(View.GONE);
        switch (id){
            case R.id.train_layout:
                trainLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.exam_layout:
                examLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.employee_layout:
                employeeLayout.setVisibility(View.VISIBLE);
                break;
            default:
                trainLayout.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void initDate(){
        Calendar calendar = Calendar.getInstance();
        stopDay = dateformat(calendar);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        startDay = dateformat(calendar);

        processDate();
    }

    private DayTimeEntity dateformat(Calendar calendar){
        DayTimeEntity dayTimeEntity = new DayTimeEntity(calendar.get(Calendar.DAY_OF_MONTH),
                calendar.get(Calendar.MONTH) + 1,
                calendar.get(Calendar.YEAR));
        return dayTimeEntity;
    }

    private void showChart(int id){
        barChart.setVisibility(View.GONE);
        pieChart.setVisibility(View.GONE);
        pieLegendList.clear();
        pieAdapter.setDataList(pieLegendList);
        switch (id){
            case R.id.bar_chart:
                barChart.setVisibility(View.VISIBLE);
                break;
            case R.id.pie_chart:
                pieChart.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    /**
     * 初始化BarChart图表
     */
    private void initBarChart(BarChart barChart) {
        /***图表设置***/
        //背景颜色
        barChart.setBackgroundColor(Color.WHITE);
        //不显示图表网格
        barChart.setDrawGridBackground(false);
        //背景阴影
        barChart.setDrawBarShadow(false);
        barChart.setHighlightFullBarEnabled(false);

        barChart.setDoubleTapToZoomEnabled(false);
        //禁止拖拽
        barChart.setDragEnabled(false);
        //X轴或Y轴禁止缩放
        barChart.setScaleXEnabled(false);
        barChart.setScaleYEnabled(false);
        barChart.setScaleEnabled(false);
        //禁止所有事件
//        barChart.setTouchEnabled(false);


        //不显示边框
        barChart.setDrawBorders(false);

        //不显示右下角描述内容
        Description description = new Description();
        description.setEnabled(false);
        barChart.setDescription(description);

        //设置动画效果
        barChart.animateY(1000, Easing.Linear);
        barChart.animateX(1000, Easing.Linear);

        /***XY轴的设置***/
        //X轴设置显示位置在底部
        xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);

        leftAxis = barChart.getAxisLeft();
        rightAxis = barChart.getAxisRight();


//        xAxis.setAxisMinimum(0f);
        //保证Y轴从0开始，不然会上移一点
//        leftAxis.setAxisMinimum(0f);
//        rightAxis.setAxisMinimum(0f);

        //不绘制X Y轴线条
        xAxis.setDrawAxisLine(false);
        leftAxis.setDrawAxisLine(false);
        rightAxis.setDrawAxisLine(false);
        //不显示左侧Y轴
        rightAxis.setEnabled(false);

        //不显示X轴网格线
        xAxis.setDrawGridLines(false);
        //右侧Y轴网格线设置为虚线
        leftAxis.enableGridDashedLine(10f, 10f, 0f);

        /***折线图例 标签 设置***/
        legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
        legend.setEnabled(false);

        pieLegendList = new ArrayList<>();
        pieAdapter = new LegendAdapter(this, pieLegendList);
        pieChartLegendRv.setAdapter(pieAdapter);
        pieChartLegendRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        pieChartLegendRv.setItemAnimator(new DefaultItemAnimator());
    }

    @OnClick({R.id.iv_back, R.id.total_person_now, R.id.total_person_history, R.id.total_person_train, R.id.train_percent, R.id.total_train,
            R.id.total_train_hour, R.id.avg_person_train_hour, R.id.total_person_exam, R.id.total_exam_pass, R.id.exam_pass_percent, R.id.start_end_date})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.start_end_date:
                Intent intent = new Intent(this, TimePickerActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.total_person_now:
                type = 9;
                nameTv.setText(R.string.total_person_now);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.total_person_history:
                type = 10;
                nameTv.setText(R.string.total_person_history);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.total_person_train:
                type = 1;
                nameTv.setText(R.string.total_person_train);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.train_percent:
                type = 2;
                nameTv.setText(R.string.train_percent);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.total_train:
                type = 3;
                nameTv.setText(R.string.total_train);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.total_train_hour:
                type = 4;
                nameTv.setText(R.string.total_train_hour);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.avg_person_train_hour:
                type = 5;
                nameTv.setText(R.string.avg_person_train_hour);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.total_person_exam:
                type = 6;
                nameTv.setText(R.string.total_person_exam);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.total_exam_pass:
                type = 7;
                nameTv.setText(R.string.total_exam_pass);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
            case R.id.exam_pass_percent:
                type = 8;
                nameTv.setText(R.string.exam_pass_percent);
                getCreateChart();//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode == 0 && data != null){
                startDay = (DayTimeEntity) data.getSerializableExtra("startDay");
                stopDay = (DayTimeEntity) data.getSerializableExtra("stopDay");
                processDate();
            }
        }
    }

    private void processDate(){
        startTime = dateFormat(startDay);
        endTime = dateFormat(stopDay);
        startDndDate.setText(dateFormatExceptYear(startDay) + "起—" + dateFormatExceptYear(stopDay) + "止");
        getTrainPersonTotalDetail();
        getCreateChart();
        if(type == 1 || type == 2 || type == 3 || type == 4 || type == 5){
            showLayout(R.id.train_layout);
            showChart(R.id.bar_chart);
        }else if (type == 6 || type == 7 || type == 8){
            showLayout(R.id.exam_layout);
            showChart(R.id.bar_chart);
        }else {
            showLayout(R.id.employee_layout);
            showChart(R.id.pie_chart);
        }
    }

    private String dateFormat(DayTimeEntity dayTimeEntity){
        StringBuffer dateSb = new StringBuffer();
        dateSb.append(dayTimeEntity.getYear() + "-");
        if(dayTimeEntity.getMonth() > 9){
            dateSb.append(dayTimeEntity.getMonth() + "-");
        }else {
            dateSb.append( "0" + dayTimeEntity.getMonth() + "-");
        }
        if(dayTimeEntity.getDay() > 9){
            dateSb.append(dayTimeEntity.getDay());
        }else {
            dateSb.append( "0" + dayTimeEntity.getDay());
        }
        return dateSb.toString();
    }

    private String dateFormatExceptYear(DayTimeEntity dayTimeEntity){
        StringBuffer dateSb = new StringBuffer();
        dateSb.append(dayTimeEntity.getYear() + "/");
        if(dayTimeEntity.getMonth() > 9){
            dateSb.append(dayTimeEntity.getMonth() + "/");
        }else {
            dateSb.append( "0" + dayTimeEntity.getMonth() + "/");
        }
        if(dayTimeEntity.getDay() > 9){
            dateSb.append(dayTimeEntity.getDay());
        }else {
            dateSb.append( "0" + dayTimeEntity.getDay());
        }
        return dateSb.toString();
    }

    private void getTrainPersonTotalDetail(){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
            jsonObject.put("departId", SPUtil.getString(this,"constructionid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/thridPerson/getTrainPersonTotalDetail/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(!Utils.isEmpty(json)){
                    Gson gson = new Gson();
                    StatisticsRes statisticsRes = gson.fromJson(json, StatisticsRes.class);
                    if(statisticsRes.getStatus() == 1){
                        processStatistics(statisticsRes.getValue());
                    }else {
                        showToast(statisticsRes.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }

            }

            @Override
            public void onFailure(String json) {
//                Log.e(TAG, "CarManagementActivity===>>>" + json);
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast(R.string.system_erro);
                }
            }
        });
    }

    private void processStatistics(Statistics datas){
        totalPersonNowTv.setText(datas.getTotalPersonNow());
        totalPersonHistoryTv.setText(datas.getTotalPersonHistory());
        totalPersonTrainTv.setText(datas.getTotalPersonTrain());
        trainPercentTv.setText(datas.getTrainPercent());
        totalTrainTv.setText(datas.getTotalTrain());
        totalTrainHourTv.setText(datas.getTotalTrainHour());
        avgPersonTrainHourTv.setText(datas.getAvgPersonTrainHour());
        totalPersonExamTv.setText(datas.getTotalPersonExam());
        totalExamPassTv.setText(datas.getTotalExamPass());
        examPassPercentTv.setText(datas.getExamPassPercent());

        totalPersonNow.setText(datas.getTotalPersonNow());
        totalPersonHistory.setText(datas.getTotalPersonHistory());
        totalPersonTrain.setText(datas.getTotalPersonTrain());
        trainPercent.setText(datas.getTrainPercent());
        totalTrain.setText(datas.getTotalTrain());
        totalTrainHour.setText(datas.getTotalTrainHour());
        avgPersonTrainHour.setText(datas.getAvgPersonTrainHour());
        totalPersonExam.setText(datas.getTotalPersonExam());
        totalExamPass.setText(datas.getTotalExamPass());
        examPassPercent.setText(datas.getExamPassPercent());
    }

    private void getCreateChart(){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", type);//(type 1 培训人数 2 培训率 3 培训人次 4 累计学时 5 人均学时 6 考试人次 7 合格人次 8 合格率 9 现有总人数 10 历史总人数) 9和10是饼状图，其他是柱状图
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
            jsonObject.put("departId", SPUtil.getString(this,"constructionid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData("加载中…", this, "/thridPerson/getCreateChart/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(!Utils.isEmpty(json)){
                    Gson gson = new Gson();
                    StatisticsChartBeanRes chartRes = gson.fromJson(json, StatisticsChartBeanRes.class);
                    if(chartRes.getStatus() == 1){
                        if(type == 9 || type == 10){
                            if(chartRes.getValue() == null || chartRes.getValue().size() <= 0){
                                showChart(R.id.pie_chart);
                                MPChartUtils.NotShowNoDataText(pieChart);
                            }else {
                                processPieChart(chartRes.getValue());
                            }
                        }else {
                            if(chartRes.getValue() == null || chartRes.getValue().size() <= 0){
                                showChart(R.id.bar_chart);
                                MPChartUtils.NotShowNoDataText(barChart);
                            }else {
                                processBarChart(chartRes.getValue());
                            }
                        }
                    }else{
                        if(type == 9 || type == 10){
                            showChart(R.id.pie_chart);
                            MPChartUtils.NotShowNoDataText(pieChart);
                        }else {
                            showChart(R.id.bar_chart);
                            MPChartUtils.NotShowNoDataText(barChart);
                        }
                    }
                }else{
                    showToast("系统异常");
                    if(type == 9 || type == 10){
                        showChart(R.id.pie_chart);
                        MPChartUtils.NotShowNoDataText(pieChart);
                    }else {
                        showChart(R.id.bar_chart);
                        MPChartUtils.NotShowNoDataText(barChart);
                    }
                }

            }

            @Override
            public void onFailure(String json) {
//                Log.e(TAG, "CarManagementActivity===>>>" + json);
                if(type == 9 || type == 10){
                    showChart(R.id.pie_chart);
                    MPChartUtils.NotShowNoDataText(pieChart);
                }else {
                    showChart(R.id.bar_chart);
                    MPChartUtils.NotShowNoDataText(barChart);
                }
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast(R.string.system_erro);
                }
            }
        });
    }

    private void processPieChart(List<StatisticsChartBean> datas){
        showChart(R.id.pie_chart);
        List<String> names = new ArrayList<>(); //每个模块的内容描述
        for (int i = 0; i < datas.size(); i++) {
            names.add(datas.get(i).getName());
        }
        List<Float> data = new ArrayList<>(); //每个模块的值（占比率）
        for (int i = 0; i < datas.size(); i++) {
            data.add(datas.get(i).getQty().get(0));
        }
        pieLegendList.add(new LegendBean(R.drawable.legend_pink, names.get(0) + "员工人数" + data.get(0) + "人"));
        pieLegendList.add(new LegendBean(R.drawable.legend_light_yellow, names.get(1) + "员工人数" + data.get(1) + "人"));
        pieAdapter.setDataList(pieLegendList);
        List<Integer> colors = new ArrayList<>(); //每个模块的颜色
        colors.add(getResources().getColor(R.color.color_ffaeae));
        colors.add(getResources().getColor(R.color.color_fbd44c));
        //饼状图管理类
        PieChartManager pieChartManager = new PieChartManager(pieChart);
        pieChartManager.setPieChart(names, data, colors);
    }

    private void processBarChart(List<StatisticsChartBean> datas){
        showChart(R.id.bar_chart);
        //处理数据是 记得判断每条柱状图对应的数据集合 长度是否一致
        LinkedHashMap<String, List<Float>> chartDataMap = new LinkedHashMap<>();
        List<String> xValues = new ArrayList<>();
        List<Float> yValue1 = new ArrayList<>();
        List<Float> yValue2 = new ArrayList<>();
        List<Integer> colors = null;

        List<ChartBean> trainList = new ArrayList<>();
        List<ChartBean> totalList = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            StatisticsChartBean bean = datas.get(i);
            ChartBean trainBean = new ChartBean(bean.getName(), bean.getQty().get(0));
            trainList.add(trainBean);
            if(bean.getQty().size() > 1){
                ChartBean totalBean = new ChartBean(bean.getName(), bean.getQty().get(1));
                totalList.add(totalBean);
            }
        }
        for (ChartBean chartBean : trainList) {
            xValues.add(chartBean.getName());
            yValue1.add(chartBean.getValue());
        }
        for (ChartBean chartBean : totalList) {
            yValue2.add(chartBean.getValue());
        }

        String name1 = "培训人数",
                name2 = "员工人数";
        switch (type){
            case 1:
                name1 = "培训人数";
                name2 = "员工人数";
                colors = Arrays.asList(getResources().getColor(R.color.color_FFCC89), getResources().getColor(R.color.color_93c4f2));
                break;
            case 2:
                name1 = "培训率";
                colors = Arrays.asList(getResources().getColor(R.color.color_FFCC89), getResources().getColor(R.color.color_93c4f2));
                break;
            case 3:
                name1 = "培训人次";
                colors = Arrays.asList(getResources().getColor(R.color.color_FFCC89), getResources().getColor(R.color.color_93c4f2));
                break;
            case 4:
                name1 = "培训学时";
                colors = Arrays.asList(getResources().getColor(R.color.color_d3a9ff), getResources().getColor(R.color.color_93c4f2));
                break;
            case 5:
                name1 = "人均学时";
                colors = Arrays.asList(getResources().getColor(R.color.color_d3a9ff), getResources().getColor(R.color.color_93c4f2));
                break;
            case 6:
                name1 = "考试人次";
                colors = Arrays.asList(getResources().getColor(R.color.color_ff9177), getResources().getColor(R.color.color_93c4f2));
                break;
            case 7:
                name1 = "合格人次";
                colors = Arrays.asList(getResources().getColor(R.color.color_87dc8d), getResources().getColor(R.color.color_93c4f2));
                break;
            case 8:
                name1 = "考试合格率";
                colors = Arrays.asList(getResources().getColor(R.color.color_87dc8d), getResources().getColor(R.color.color_93c4f2));
                break;
        }

        chartDataMap.put(name1, yValue1);
        chartDataMap.put(name2, yValue2);

        showBarChart(xValues, chartDataMap, colors);
    }

    /**
     * @param xValues   X轴的值
     * @param dataLists LinkedHashMap<String, List<Float>>
     *                  key对应柱状图名字  List<Float> 对应每类柱状图的Y值
     * @param colors
     */
    public void showBarChart(final List<String> xValues, LinkedHashMap<String, List<Float>> dataLists,
                             @ColorRes List<Integer> colors) {

        List<IBarDataSet> dataSets = new ArrayList<>();
        int currentPosition = 0;//用于柱状图颜色集合的index

        for (LinkedHashMap.Entry<String, List<Float>> entry : dataLists.entrySet()) {
            String name = entry.getKey();
            List<Float> yValueList = entry.getValue();

            List<BarEntry> entries = new ArrayList<>();

            for (int i = 0; i < yValueList.size(); i++) {
                /**
                 *  如果需要添加TAG标志 可使用以下构造方法
                 *  BarEntry(float x, float y, Object data)
                 *  e.getData()
                 */
                entries.add(new BarEntry(i, yValueList.get(i)));
            }
            // 每一个BarDataSet代表一类柱状图
            BarDataSet barDataSet = new BarDataSet(entries, name);
            initBarDataSet(barDataSet, colors.get(currentPosition));
            dataSets.add(barDataSet);

            currentPosition++;
        }

//X轴自定义值
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xValues.get((int) Math.abs(value) % xValues.size());
            }
        });
        //右侧Y轴自定义值
        rightAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return (int) (value) + "";
            }
        });

        BarData data = new BarData(dataSets);

        /**
         * float groupSpace = 0.3f;   //柱状图组之间的间距
         * float barSpace =  0.05f;  //每条柱状图之间的间距  一组两个柱状图
         * float barWidth = 0.3f;    //每条柱状图的宽度     一组两个柱状图
         * (barWidth + barSpace) * 2 + groupSpace = (0.3 + 0.05) * 2 + 0.3 = 1.00
         * 3个数值 加起来 必须等于 1 即100% 按照百分比来计算 组间距 柱状图间距 柱状图宽度
         */
        int barAmount = dataLists.size(); //需要显示柱状图的类别 数量
        //设置组间距占比30% 每条柱状图宽度占比 70% /barAmount  柱状图间距占比 0%
        float groupSpace, barWidth;
        if(barAmount >= 5){
            groupSpace = 0.3f; //柱状图组之间的间距
            barWidth = (1f - groupSpace) / barAmount;
        }else {
            barWidth = 0.2f;
            groupSpace = 1 - (barAmount * barWidth);
        }
        float barSpace = 0f;
        //设置柱状图宽度
        data.setBarWidth(barWidth);
        //(起始点、柱状图组间距、柱状图之间间距)
        data.groupBars(0f, groupSpace, barSpace);
        barChart.setData(data);

        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(xValues.size());
        //将X轴的值显示在中央
        xAxis.setCenterAxisLabels(true);
    }

    /**
     * 柱状图始化设置 一个BarDataSet 代表一列柱状图
     *
     * @param barDataSet 柱状图
     * @param color      柱状图颜色
     */
    private void initBarDataSet(BarDataSet barDataSet, int color) {
        barDataSet.setColor(color);
//        barDataSet.setFormLineWidth(1f);
//        barDataSet.setFormSize(15.f);
        //不显示柱状图顶部值
        barDataSet.setDrawValues(false);
//        barDataSet.setValueTextSize(10f);
//        barDataSet.setValueTextColor(color);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.train_statistics_rb:
                showLayout(R.id.train_layout);
                type = 1 ;
                nameTv.setText(R.string.total_person_train);
                getCreateChart();
                break;
            case R.id.exam_statistics_rb:
                showLayout(R.id.exam_layout);
                type = 6 ;
                nameTv.setText(R.string.total_person_exam);
                getCreateChart();
                break;
            case R.id.employee_statistics_rb:
                showLayout(R.id.employee_layout);
                type = 9 ;
                nameTv.setText(R.string.total_person_now);
                getCreateChart();
                break;
        }
        showChart(-1);
    }
}
